﻿Imports System.ComponentModel.Composition.Hosting
Imports System.IO
Imports System.Runtime.CompilerServices
Imports System.Reflection
Imports System.ComponentModel.Composition

Module AppHelper
    ''' <summary>
    ''' Performs MEF addin composition
    ''' </summary>
    ''' <returns></returns>
    <Extension()> _
    Public Function Compose(ByVal app As System.Windows.Application, ByVal o As Object) As Boolean
        Dim MyApp As WpfAppHost.Application = app

        ' Builds up addin catalog
        If MyApp._container Is Nothing Then
            Dim catalog As New AggregateCatalog()

            catalog.Catalogs.Add(New AssemblyCatalog(Assembly.GetExecutingAssembly()))

            ' See if any DLL's in the addins folder
            Dim addinsDir As String = System.IO.Path.Combine(Environment.CurrentDirectory, "addins")

            If Directory.Exists(addinsDir) Then
                catalog.Catalogs.Add(New DirectoryCatalog(addinsDir, "*.dll"))
            End If

            MyApp._container = New CompositionContainer(catalog)
        End If

        'Dim batch As New CompositionBatch()
        'batch.AddPart(o)

        Try
            'MyApp._container.Compose(batch)
        Catch compositionException As ComponentModel.Composition.CompositionException
            MessageBox.Show(compositionException.ToString())
            Return False
        End Try

        If MyApp._container.Catalog.Parts.Count > 0 Then

            Dim x As System.Collections.ObjectModel.Collection(Of Contracts.IWpfService) = MyApp._container.GetExportedObjects(Of Contracts.IWpfService)()

            Dim ex As ExportCollection(Of Contracts.IWpfService) = MyApp._container.GetExports(Of Contracts.IWpfService)()

            If ex.Count > 0 Then
                Debug.WriteLine("")
                Debug.WriteLine(GetMetadataValue(ex.Item(0).Metadata, "ServiceName"))
                Debug.WriteLine("")
            End If

        End If


        Return True
    End Function

    Public Function GetMetadataValue(ByVal m As Generic.IDictionary(Of String, Object), ByVal key As String) As String
        Dim value As String = String.Empty
        Dim oVal As Object = Nothing

        m.TryGetValue(key, oVal)
        If Not oVal Is Nothing Then value = oVal.ToString()

        Return value
    End Function

End Module
